package com.ruicar.afs.cloud.apply.archive.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.apply.archive.condition.ImageCondition;
import com.ruicar.afs.cloud.apply.archive.condition.PostCondition;
import com.ruicar.afs.cloud.apply.archive.enums.WayBillEnum;
import com.ruicar.afs.cloud.apply.archive.service.WaybillService;
import com.ruicar.afs.cloud.archive.dto.DocumentDto;
import com.ruicar.afs.cloud.archive.dto.ImageDto;
import com.ruicar.afs.cloud.archive.dto.PostDto;
import com.ruicar.afs.cloud.archive.feign.ArchiveApiFeign;
import com.ruicar.afs.cloud.archive.result.ArchiveCommon.ArchivedAnchored;
import com.ruicar.afs.cloud.archive.result.ArchiveCommon.ArchivedPicture;
import com.ruicar.afs.cloud.archive.result.ArchiveCommon.ArchivedUpload;
import com.ruicar.afs.cloud.archive.result.ArchiveDocListDto.ArchivedDocDetail;
import com.ruicar.afs.cloud.archive.result.ArchiveDocListDto.ArchivedDocEdit;
import com.ruicar.afs.cloud.archive.result.ArchivePostDetailDto.ArchivedPostNew;
import com.ruicar.afs.cloud.archive.result.ArchivePostFileListDto.ArchivedPostFileDetail;
import com.ruicar.afs.cloud.archive.result.ArchivedPageDto;
import com.ruicar.afs.cloud.archive.result.ArchivedResultDto;
import com.ruicar.afs.cloud.archive.service.ArchiveService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @description: 运单服务类
 * @author: sijun.yu
 * @date: 2020/6/5 14:20
 */
@Service
@AllArgsConstructor
@Slf4j
public class WaybillServiceImpl implements WaybillService {

    private ArchiveApiFeign archiveApiFeign;
    private ArchiveService archiveService;

    /**
     * 获取token信息
     *
     * @return
     */
    public String getAuthorization() {
        //String authorization = paramConfigService.getParamValue("archive","token","");
        String authorization = archiveService.getAuthorization();
        return authorization;
    }

    /**
     * 获取归档列表
     *
     * @param condition
     * @return
     */
    public IResponse getDocList(PostCondition condition) {

        DocumentDto dto = new DocumentDto();
        dto.setCategory(condition.getCategory());
        dto.setPageIndex(condition.getPageIndex());
        dto.setPageSize(condition.getPageSize());
        dto.setKey(condition.getKey());
        dto.setStatus(condition.getStatus());

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());

        try {
            ArchivedResultDto json =  archiveApiFeign.getDocList(dto, headers);
            if(1==json.getSuccess()){
                ArchivedPageDto archivedPageDto = JSON.parseObject(JSON.toJSONString(json.getData()), ArchivedPageDto.class);
                List<ArchivedDocDetail> list = JSON.parseArray(JSON.toJSONString(archivedPageDto.getData()), ArchivedDocDetail.class);
                //分页处理
                IPage iPage = new Page();
                iPage.setRecords(list);
                iPage.setPages(archivedPageDto.getPageIndex());
                iPage.setSize(archivedPageDto.getPageSize());
                iPage.setTotal(archivedPageDto.getRecordsTotal());
                return IResponse.success(iPage);
            }else{
                return IResponse.fail(json.getMessage());
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }
    }

    /**
     * 保存运单信息
     *
     * @param condition
     * @return
     */
    public IResponse savePostInfo(PostCondition condition) {

        JSONObject jsonPut = new JSONObject();
        jsonPut.put("postNo",condition.getPostNo());
        jsonPut.put("pDate",condition.getPostDate());
        jsonPut.put("pCompany",condition.getPostCompany());
        jsonPut.put("postImgMd5",condition.getPostImgMd5());
        jsonPut.put("memo",condition.getMemo());
        jsonPut.put("ID",condition.getId());

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());
        try {
            //ID为空时，创建运单
            if(StringUtils.isEmpty(condition.getId())){
                ArchivedResultDto archivedResultDto =  archiveApiFeign.newPost(headers);
                ArchivedPostNew archivedPostNew = JSON.parseObject(JSON.toJSONString(archivedResultDto.getData()), ArchivedPostNew.class);
            }
            ArchivedResultDto json =  archiveApiFeign.savePost(jsonPut, headers);
            if(1==json.getSuccess()){
                return IResponse.success(json.getData());
            }else{
                return IResponse.fail(json.getMessage());
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }
    }

    /**
     * 查找最新运单
     *
     * @return
     */
    public IResponse getPostInfo() {

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());

        try {
            ArchivedResultDto json =  archiveApiFeign.getLastPost(headers);
            if(1==json.getSuccess()){
                return IResponse.success(json.getData());
            }else{
                JSONObject jsonResult = new JSONObject();
                jsonResult.put("id",null);
                return IResponse.success(jsonResult);
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }
    }

    /**
     * 编辑运单信息
     *
     * @return
     */
    public IResponse editPostInfo(PostCondition condition) {

        PostDto dto = new PostDto();
        dto.setId(condition.getId());

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());

        try {
            ArchivedResultDto json =  archiveApiFeign.editPost(dto, headers);
            if(1==json.getSuccess()){
                return IResponse.success(json.getData());
            }else{
                return IResponse.fail(json.getMessage());
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }

    }

    /**
     * 编辑查看归档信息
     *
     * @param condition
     * @return
     */
    public IResponse editDocInfo(PostCondition condition) {

        DocumentDto dto = new DocumentDto();
        dto.setCacontractId(condition.getCacontractId());
        dto.setIsEdit(condition.getIsEdit());
        dto.setIsNotPost(condition.getIsNotPost());

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());
        try {
            ArchivedResultDto archivedResultDto =  archiveApiFeign.editDocInfo(dto, headers);
            if(1==archivedResultDto.getSuccess()){
                ArchivedDocEdit archivedDocEdit = JSON.parseObject(JSON.toJSONString(archivedResultDto.getData()), ArchivedDocEdit.class);
                List<ArchivedPicture> impictureMd5List = new ArrayList();
                List<ArchivedPicture> archivedDocEditPictureList = archivedDocEdit.getPictureList();
                BASE64Encoder encoder = new BASE64Encoder();
                for(ArchivedPicture archivedPicture : archivedDocEditPictureList){
                    ImageCondition imageCondition = new ImageCondition();
                    imageCondition.setMd5(archivedPicture.getMd5());
                    byte[] md5 = this.downFile(imageCondition);
                    archivedPicture.setMd5Byte(encoder.encode(md5));
                    impictureMd5List.add(archivedPicture);
                }
                archivedDocEdit.setMd5List(impictureMd5List);
                return IResponse.success(archivedDocEdit);
            }else{
                return IResponse.fail(archivedResultDto.getMessage());
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }
    }

    /**
     * 提交归档信息
     *
     * @param condition
     * @return
     */
    public IResponse submitDocInfo(PostCondition condition) {

        DocumentDto dto = new DocumentDto();
        dto.setPostId(condition.getPostId());
        dto.setCacontractId(condition.getCacontractId());
        dto.setApplicationNo(condition.getApplicationNo());
        dto.setPlateNo(condition.getPlateNo());
        dto.setPledgeDate(condition.getPledgeDate());
        dto.setCodes(condition.getCodes());
        dto.setDcpostId(condition.getDcpostId());
        dto.setDcpostFileNames(condition.getDcpostFileNames());
        dto.setDcpostFileOthername(condition.getDcpostFileOthername());
        dto.setIsCheckLv(condition.getIsCheckLv());

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());

        try {
            ArchivedResultDto json =  archiveApiFeign.submitDocInfo(dto, headers);
            if(1==json.getSuccess()){
                return IResponse.success(json.getData());
            }else{
                return IResponse.fail(json.getMessage());
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }

    }

    /**
     * 查询运单的归档列表
     *
     * @return
     */
    public IResponse getPostDocList(PostCondition condition) {

        PostDto dto = new PostDto();
        dto.setDcpostId(condition.getDcpostId());
        dto.setPageIndex(condition.getPageIndex());
        dto.setPageSize(condition.getPageSize());

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());

        try {
            ArchivedResultDto json =  archiveApiFeign.getPostDocList(dto, headers);
            if(1==json.getSuccess()){
                ArchivedPageDto archivedPageDto = JSON.parseObject(JSON.toJSONString(json.getData()), ArchivedPageDto.class);
                List<ArchivedPostFileDetail> list = JSON.parseArray(JSON.toJSONString(archivedPageDto.getData()), ArchivedPostFileDetail.class);
                //分页处理
                IPage iPage = new Page();
                iPage.setRecords(list);
                iPage.setPages(archivedPageDto.getPageIndex());
                iPage.setSize(archivedPageDto.getPageSize());
                iPage.setTotal(archivedPageDto.getRecordsTotal());
                return IResponse.success(iPage);
            }else{
                return IResponse.fail(json.getMessage());
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }
    }

    /**
     * 删除运单的归档
     *
     * @return
     */
    public IResponse deletePostDocInfo(PostCondition condition) {

        PostDto dto = new PostDto();
        dto.setId(condition.getId());

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());

        try {
            ArchivedResultDto json =   archiveApiFeign.deletePostDocInfo(dto, headers);
            if(1==json.getSuccess()){
                return IResponse.success(true);
            }else{
                return IResponse.fail(json.getMessage());
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }
    }

    /**
     * 提交运单信息
     *
     * @param condition
     * @return
     */
    public IResponse submitPostInfo(PostCondition condition) {

        PostDto dto = new PostDto();
        dto.setId(condition.getId());

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());

        try {
            ArchivedResultDto json =   archiveApiFeign.submitPost(dto, headers);
            if(1==json.getSuccess()){
                return IResponse.success(true);
            }else{
                return IResponse.fail(json.getMessage());
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }

    }

    /**
     * 创建运单信息
     * @return
     */
    @Override
    public IResponse newPost() {
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());

        try {
            ArchivedResultDto json =  archiveApiFeign.newPost(headers);
            if(1==json.getSuccess()){
                return IResponse.success(json.getData());
            }else{
                return IResponse.fail(json.getMessage());
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }
    }

    /**
     * 获取挂靠信息
     * @param condition
     * @return
     */
    public IResponse getanchoredinfo(PostCondition condition) {

        PostDto dto = new PostDto();
        dto.setApplicationNo(condition.getApplicationNo()); //类型：String  必有字段  备注：申请编号（前端用）

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());
        try {
            ArchivedResultDto json =  archiveApiFeign.getanchoredinfo(dto, headers);
            if(1==json.getSuccess()){
                ArchivedAnchored archivedAnchored = JSON.parseObject(JSON.toJSONString(json.getData()), ArchivedAnchored.class);
                return IResponse.success(archivedAnchored);
            }else{
                return IResponse.fail(json.getMessage());
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }
    }

    /**
     * 判断是否免抵押退回绿本
     *
     * @param condition
     * @return
     */
    @Override
    public IResponse checkPostDoc(PostCondition condition) {

        PostDto dto = new PostDto();
        dto.setApplicationNo(condition.getApplicationNo()); //类型：String  必有字段  备注：申请编号（前端用）
        dto.setDcpostId(condition.getDcpostId()); //类型：String  必有字段  备注： 提交归档信息DCPOST邮寄信息表id对应前台原postfile.dcpostid （前端用）

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());
        try {
            ArchivedResultDto json =  archiveApiFeign.checkPostDoc(dto, headers);
            if(1==json.getSuccess()){
                return IResponse.success(json.getData());
            }else{
                return IResponse.fail(json.getMessage());
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }
    }

    /**
     * 文件下载
     * @param condition
     * @return
     */
    @Override
    public byte[] downFile(ImageCondition condition) {
        JSONObject json = new JSONObject();
        json.put("md5",condition.getMd5());

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());
        byte[] result = null;
        try {
            result =  archiveApiFeign.downFile(json, headers);
        }catch (Exception e){
            Assert.isTrue(false, e.toString());
        }
        return result;
    }

    /**
     * 文件上传
     * @return
     */
    @Override
    public IResponse upload(MultipartFile file,String camainId,String imCategoryCode) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", getAuthorization());
        String randomstr = DateUtil.format(DateUtil.date(),DatePattern.PURE_DATETIME_MS_PATTERN);//唯一串
        String sceneid = AfsEnumUtil.key(WayBillEnum.SCENEID_ARCHIVE);//上传类型

        try {
            ArchivedResultDto archivedResultDto =  archiveApiFeign.upload(sceneid,randomstr,file, headers);
            if(1==archivedResultDto.getSuccess()){

                ArchivedUpload archivedUpload = JSON.parseObject(JSON.toJSONString(archivedResultDto.getData()), ArchivedUpload.class);

                String scene = AfsEnumUtil.key(WayBillEnum.SCENE);//场景
                String isCap = AfsEnumUtil.key(WayBillEnum.ISCAP);//是否高拍仪
                String status = AfsEnumUtil.key(WayBillEnum.STATUS);//提交状态

                ImageDto dto = new ImageDto();
                dto.setMd5(archivedUpload.getMd5()); //类型：String  必有字段  备注：Md5
                dto.setRandomStr(archivedUpload.getRandomstr());//类型：String  必有字段  备注：唯一随机串
                dto.setSize(archivedUpload.getSize());//类型：Number  必有字段  备注：文件大小
                dto.setImCategoryCode(imCategoryCode);//类型：String  必有字段  备注：文件类型
                dto.setCamainId(camainId); //类型：String  必有字段  备注：案件id
                dto.setStatus(Integer.parseInt(status));//类型：Number  必有字段  备注：提交状态
                dto.setScene(Integer.parseInt(scene)); //类型：Number  必有字段  备注：场景
                dto.setIsCap(Integer.parseInt(isCap)); //类型：Number  必有字段  备注：是否高拍仪
                dto.setName(null);//类型：String  必有字段  备注：文件名称
                dto.setCUser(null); //类型：String  必有字段  备注：创建人
                dto.setUploadFrom(null);//类型：Number  必有字段  备注：图片途径
                dto.setMidId(null);//类型：String  必有字段  备注：中间件标识
                dto.setOldRandomStr(null);//类型：String  必有字段  备注：旧的唯一随机串
                dto.setSuccess(null); //类型：String  必有字段  备注：上传成功标志

                ArchivedResultDto jsonDcsaveinfo =  archiveApiFeign.dcsaveinfo(dto, headers);
                if(1==jsonDcsaveinfo.getSuccess()){
                    return IResponse.success(archivedUpload);
                }else{
                    return IResponse.fail(jsonDcsaveinfo.getMessage());
                }
            }else{
                return IResponse.fail(archivedResultDto.getMessage());
            }
        }catch (Exception e){
            return IResponse.fail("接口异常，请联系管理员！");
        }
    }

}
